package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/status"
	"rpc_demo/rpc_interceptor/proto"
	"time"
)

type custormCredentials struct {
	appid  string
	appkey string
}

func (a *custormCredentials) GetRequestMetadata(context.Context, ...string) (
	map[string]string, error,
) {
	return map[string]string{"appid": "dasfds", "appkey": "dasfdsf"}, nil
}
func (a *custormCredentials) RequireTransportSecurity() bool {
	return false
}

type D struct {
	appid  string
	appkey string
}

func main() {

	//interceptor := func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
	//
	//	pairs := metadata.Pairs(
	//		"appid", "234",
	//		"appkey", "king",
	//	)
	//	outgoingContext := metadata.NewOutgoingContext(ctx, pairs)
	//	err := invoker(outgoingContext, method, req, reply, cc, opts...)
	//	if err != nil {
	//		panic(err)
	//	}
	//	return err
	//}

	d := custormCredentials{
		appid:  "234",
		appkey: "king",
	}
	var opts []grpc.DialOption
	//opt := append(opts, grpc.RequireTransportSecurity())
	opt := append(opts, grpc.WithInsecure())
	//opt := append(opts, grpc.WithUnaryInterceptor(interceptor))
	opt = append(opts, grpc.WithPerRPCCredentials(&d))
	opt = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
	//client, err := grpc.Dial("localhost:50051")
	//client, err := grpc.Dial("localhost:50051", opt...)
	client, err := grpc.NewClient("localhost:50051", opt...)

	if err != nil {
		panic(err)
	}

	//defer client.Close()
	greeterClient := proto.NewHelloClient(client)
	ctx, _ := context.WithTimeout(context.Background(), time.Second*2)
	hello, err := greeterClient.SayHello(ctx, &proto.HelloReq{Data: "1"})
	if err != nil {
		s, _ := status.FromError(err)
		fmt.Println("###")
		fmt.Println(s.Message())
		fmt.Println(s.Code())
		return
	}
	fmt.Println(hello)

}
